//
//  GroupInfoViewController.m
//  WildFireChat
//
//  Created by heavyrain lee on 2019/3/3.
//  Copyright © 2019 WildFireChat. All rights reserved.
//

#import "WFCUGroupInfoViewController.h"
#import <WFChatClient/WFCChatClient.h>
#import <SDWebImage/SDWebImage.h>
#import "WFCUConfigManager.h"
#import "WFCUImage.h"
#import "WFCUMessageListViewController.h"
#import "UIView+Toast.h"
#import "YGExtendChain.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"
@interface WFCUGroupInfoViewController ()
@property (nonatomic, strong)WFCCGroupInfo *groupInfo;
@property (nonatomic, strong)UIImageView *groupProtraitView;
@property (nonatomic, strong)UILabel *groupNameLabel;
@property (nonatomic, strong)NSArray<WFCCGroupMember *> *members;
@property (nonatomic, strong)UIButton *btn;
@property (nonatomic, assign)BOOL isJoined;
@property (nonatomic, assign)int join_type;

@end

@implementation WFCUGroupInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    __weak typeof(self)ws = self;
    [[NSNotificationCenter defaultCenter] addObserverForName:kGroupInfoUpdated object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        NSArray<WFCCGroupInfo *> *groupInfoList = note.userInfo[@"groupInfoList"];
        for (WFCCGroupInfo *groupInfo in groupInfoList) {
            if ([ws.groupId isEqualToString:groupInfo.target]) {
                ws.groupInfo = groupInfo;
                break;
            }
        }

    }];
    
    
    [[NSNotificationCenter defaultCenter] addObserverForName:kGroupMemberUpdated object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        if ([ws.groupId isEqualToString:note.object]) {
            ws.members = [[WFCCIMService sharedWFCIMService] getGroupMembers:ws.groupId forceUpdate:NO];
        }
        
        
    }];
    
    [[WFCCIMService sharedWFCIMService] getGroupMembers:ws.groupId refresh:YES success:^(NSString *groupId, NSArray<WFCCGroupMember *> *members) {
        ws.members = members;
        
        [ws updateVIEW];

    } error:^(int errorCode) {
         
    }];
    [[WFCCIMService sharedWFCIMService] getGroupInfo:self.groupId  refresh:YES success:^(WFCCGroupInfo *groupInfo) {
        ws.groupInfo = groupInfo;
        [ws updateVIEW];

    } error:^(int errorCode) {
         
    }];
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    NSString *authToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"WFC_APPSERVER_AUTH_TOKEN"];
    NSString *userId = [WFCCNetworkService sharedInstance].userId;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
    //在调用其他接口时需要把cookie传给后台，也就是设置cookie的过程

    if(authToken.length) {
        [manager.requestSerializer setValue:authToken forHTTPHeaderField:@"authToken"];
 
    }
 
    
    WEAKSELF_ZM
    NSDictionary *parameters = @{@"groupId":self.groupId  }; ///<.TEXT, IMAGE, VIDEO
 
    NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/group/getGroupInfo" ];
//    {\"text\":\"文字内容\",\"imgList\":[\"http://111\",\"http://222\"],\"videoList\":[\"http:111\",\"http://222\"]}")
    [manager POST:url
       parameters:parameters
         progress:nil
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            

            NSDictionary *dic = responseObject;
            NSLog(@" ret---  %@ ", dic );
            
            if([[dic handleNullObjectForKey:@"code"] intValue] == 0) {
                
                if (weakSelf.isJoined) {
                    [weakSelf.btn setTitle:WFCString(@"StartChat") forState:UIControlStateNormal];
                } else {
                    [weakSelf.btn setTitle:WFCString(@"加入聊天") forState:UIControlStateNormal];

                }
                weakSelf.join_type = [[[dic handleNullObjectForKey:@"result"] handleNullObjectForKey:@"join_type"] intValue];
                if ( [[[dic handleNullObjectForKey:@"result"] handleNullObjectForKey:@"join_type"] intValue] == 3) {
                     
                    if (!weakSelf.isJoined) {
                         [weakSelf.btn setTitle:WFCString(@"申请加入") forState:UIControlStateNormal];

                    }

//                            weakSelf.btn.sh_chain_extend.titleColorBlack().backgroundColorClear().title(@"该群已开启进群验证 只可通过邀请进群").userInteractionEnabled(NO);
//                           
//                           CGFloat width = [UIScreen mainScreen].bounds.size.width;
//                    weakSelf.btn.frame = CGRectMake(width/2 - 120, 280, 240, 44);
//                    weakSelf.btn.titleLabel.numberOfLines = 0;
//                    weakSelf.btn.titleLabel.textAlignment = NSTextAlignmentCenter;
                    
 
                }
                if ( [[[dic handleNullObjectForKey:@"result"] handleNullObjectForKey:@"join_type"] intValue] == 1) {
                     
                    
                            weakSelf.btn.sh_chain_extend.titleColorBlack().backgroundColorClear().title(@"仅允许群成员可以拉人").userInteractionEnabled(NO);
                           
                           CGFloat width = [UIScreen mainScreen].bounds.size.width;
                    weakSelf.btn.frame = CGRectMake(width/2 - 120, 280, 240, 44);
                    weakSelf.btn.titleLabel.numberOfLines = 0;
                    weakSelf.btn.titleLabel.textAlignment = NSTextAlignmentCenter;
                    
 
                }
                if ( [[[dic handleNullObjectForKey:@"result"] handleNullObjectForKey:@"join_type"] intValue] == 2) {
                     
                    
                            weakSelf.btn.sh_chain_extend.titleColorBlack().backgroundColorClear().title(@"仅允许群管理可以拉人").userInteractionEnabled(NO);
                           
                           CGFloat width = [UIScreen mainScreen].bounds.size.width;
                    weakSelf.btn.frame = CGRectMake(width/2 - 120, 280, 240, 44);
                    weakSelf.btn.titleLabel.numberOfLines = 0;
                    weakSelf.btn.titleLabel.textAlignment = NSTextAlignmentCenter;
                    
 
                }
 
                
            }
 
            
            
        });
 
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error) {
            
            NSLog(@" ret---  %@ ", error );
            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
          
        });
        
    }];
    
    
    
}

- (void)updateVIEW{
   
    if (self.groupInfo.joinType == 3) { ///<.群成员拉入需要管理员验证>
        ///<
 
        
    }
}

- (void)setGroupInfo:(WFCCGroupInfo *)groupInfo {
    _groupInfo = groupInfo;
    if(groupInfo) {
        if(groupInfo.portrait.length) {
            __weak typeof(self)ws = self;

            self.groupProtraitView.image = [WFCUImage imageNamed:@"group_default_portrait"];
            [self.groupProtraitView sd_setImageWithURL:[NSURL URLWithString:groupInfo.portrait] placeholderImage:[WFCUImage imageNamed:@"group_default_portrait"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                if (image) {
                     
                    ws.groupProtraitView.image = image;

                }

            }];
        }
        
        self.groupNameLabel.text = [NSString stringWithFormat:@"%@(%ld)", groupInfo.displayName, groupInfo.memberCount];
    }
    
}

- (void)setMembers:(NSArray<WFCCGroupMember *> *)members {
    _members = members;
    __block BOOL isContainMe = NO;
    [members enumerateObjectsUsingBlock:^(WFCCGroupMember * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.memberId isEqualToString:[WFCCNetworkService sharedInstance].userId]) {
            *stop = YES;
            isContainMe = YES;
        }
    }];
    
    if(!isContainMe) {
        __weak typeof(self)ws = self;
        [[WFCUConfigManager globalManager].appServiceProvider getGroupMembersForPortrait:self.groupId success:^(NSArray<NSDictionary<NSString *, NSString *> *> *groupMembers) {
            [ws onGetGroupMember:groupMembers];
        } error:^(int error_code) {
            NSLog(@"error");
        }];
    }
    self.isJoined = isContainMe;
}

- (void)onGetGroupMember:(NSArray<NSDictionary<NSString *, NSString *> *> *)groupMembers {
    if(!self.groupInfo.portrait.length) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSString *imagePath = [WFCCUtilities getGroupGridPortrait:self.groupId memberPortraits:groupMembers width:50 defaultUserPortrait:^UIImage *(NSString *userId) {
                return [WFCUImage imageNamed:@"PersonalChat"];
            }];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.groupProtraitView.image = [UIImage imageWithContentsOfFile:imagePath];
            });
        });
        
    }
}

- (void)setIsJoined:(BOOL)isJoined {
    _isJoined = isJoined;
    
}

- (void)onButtonPressed:(id)sender {
    if (self.isJoined) {
        WFCUMessageListViewController *mvc = [[WFCUMessageListViewController alloc] init];
        mvc.conversation = [[WFCCConversation alloc] init];
        mvc.conversation.type = Group_Type;
        mvc.conversation.target = self.groupId;
        mvc.conversation.line = 0;
        
        mvc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:mvc animated:YES];
    } else {
        __weak typeof(self) ws = self;
        NSString *memberExtra = nil;
//        if(self.sourceType) {
//            NSDictionary *extraDict;
//            if(self.sourceTargetId.length) {
//                extraDict = @{@"s"/*source*/:@{@"t"/*type*/:@(self.sourceType), @"i"/*targetId*/:self.sourceTargetId}};
//            } else {
//                extraDict = @{@"s"/*source*/:@{@"t"/*type*/:@(self.sourceType)}};
//            }
//            
//            NSData *extraData = [NSJSONSerialization dataWithJSONObject:extraDict
//                                                                                   options:kNilOptions
//                                                                                     error:nil];
//            memberExtra = [[NSString alloc] initWithData:extraData encoding:NSUTF8StringEncoding];
//
//        }
//        if (self.groupInfo.joinType == 3) { ///<.群成员拉入需要管理员验证>
//             
//            
//            
//           WFCJoinGroupMessageContent *card = [WFCJoinGroupMessageContent cardWithTarget:self.groupId type:JoinGroup_User from:[WFCCNetworkService sharedInstance].userId];
//           
//           WFCCMessage *message = [[WFCCMessage alloc] init];
//           message.content = card;
//            
//            __strong WFCCConversation *conversation = [[WFCCConversation alloc] init];
//            conversation.type = Group_Type;
//            conversation.target = self.groupId;
//            conversation.line = 0;
//           if (message) {
//               [[WFCCIMService sharedWFCIMService] send:conversation content:message.content success:^(long long messageUid, long long timestamp) {
//                   dispatch_async(dispatch_get_main_queue(), ^{
//                       [ws.view makeToast:WFCString(@"申请成功") duration:1 position:CSToastPositionCenter];
//                       [ws.navigationController popToRootViewControllerAnimated:YES];
//                   });
//               } error:^(int error_code) {
//                   dispatch_async(dispatch_get_main_queue(), ^{
//                       [ws.view makeToast:WFCString(@"申请失败") duration:1 position:CSToastPositionCenter];
//
//                   });
//               }];
//           }
//        } else {
            
        if ( self.join_type == 3) {
            
            WEAKSELF_ZM
            __block MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.label.text = WFCString(@"加载中。。。");
            [hud showAnimated:YES];
         
            NSString *authToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"WFC_APPSERVER_AUTH_TOKEN"];
//            NSString *userId = [WFCCNetworkService sharedInstance].userId;
            
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
            
            //在调用其他接口时需要把cookie传给后台，也就是设置cookie的过程

            if(authToken.length) {
                [manager.requestSerializer setValue:authToken forHTTPHeaderField:@"authToken"];
         
            }
         
            
             
            NSDictionary *params = @{@"groupId":self.groupInfo.target,@"reason":[NSString stringWithFormat:@"请求加入:%@",self.groupInfo.name]};

            NSString *url = [NSString stringWithFormat:@"https://d.yehuoim.com/group/applyJoinGroup" ];
        //    {\"text\":\"文字内容\",\"imgList\":[\"http://111\",\"http://222\"],\"videoList\":[\"http:111\",\"http://222\"]}")
            [manager POST:url
               parameters:params
                 progress:nil
                  success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    

                    NSDictionary *dic = responseObject;
                    NSLog(@" ret---  %@ ", dic );
                    
                    if([[dic handleNullObjectForKey:@"code"] intValue] == 0) {
                        hud.hidden = YES;
                        
        //                [[WFCCIMService sharedWFCIMService] addMembers:@[groupRequest.uid] toGroup:groupRequest.gid memberExtra:nil notifyLines:@[@(0)] notifyContent:nil success:^{
                            

                        [weakSelf.view makeToast:WFCString(@"申请成功")
                                            duration:2
                                            position:CSToastPositionCenter];
                        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                        
                        
        //                } error:^(int error_code) {
        //
        //                    if (error_code == ERROR_CODE_GROUP_EXCEED_MAX_MEMBER_COUNT) {
        //                        [weakSelf.view makeToast:WFCString(@"ExceedGroupMaxMemberCount") duration:1 position:CSToastPositionCenter];
        //                    } else {
        //                        [weakSelf.view makeToast:WFCString(@"NetworkError") duration:1 position:CSToastPositionCenter];
        //                    }
        //
        //                }];
                        
         
                        
                    }else{
                        
                        hud.hidden = YES;
                        [weakSelf.view makeToast:WFCString([dic handleNullObjectForKey:@"message"]) duration:1 position:CSToastPositionCenter];
                      
                    }
                    
                    
                });
         
                
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                if (error) {
                    
                    NSLog(@" ret---  %@ ", error );
                    
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    hud.hidden = YES;

                });
                
            }];
            
            return;
        }
        
        
            [[WFCCIMService sharedWFCIMService] addMembers:@[[WFCCNetworkService sharedInstance].userId] toGroup:self.groupId memberExtra:memberExtra notifyLines:@[@(0)] notifyContent:nil success:^{
                [[WFCCIMService sharedWFCIMService] getGroupMembers:ws.groupId forceUpdate:YES];
                ws.isJoined = YES;
                [ws onButtonPressed:nil];
            } error:^(int error_code) {
                if (error_code == 248) {
                     
                    [ws.view makeToast:WFCString(@"加入失败") duration:1 position:CSToastPositionCenter];
                }
            }];
            
        
      
//        }
       
    }
}

- (UIButton *)btn {
    if (!_btn) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width;
        _btn = [[UIButton alloc] initWithFrame:CGRectMake(width/2 - 80, 280, 160, 44)];
        _btn.layer.masksToBounds = YES;
        _btn.layer.cornerRadius = 5.f;
        [self.view addSubview:_btn];
        [_btn setBackgroundColor:[UIColor colorWithRed:0.1 green:0.27 blue:0.9 alpha:0.9]];
        [_btn addTarget:self action:@selector(onButtonPressed:) forControlEvents:UIControlEventTouchDown];
    }
    return _btn;
}

- (UILabel *)groupNameLabel {
    if (!_groupNameLabel) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width;
        _groupNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(width/2 - 100, 200, 200, 24)];
        _groupNameLabel.textAlignment = NSTextAlignmentCenter;
        [self.view addSubview:_groupNameLabel];
    }
    return _groupNameLabel;
}

- (UIImageView *)groupProtraitView {
    if (!_groupProtraitView) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width;
        _groupProtraitView = [[UIImageView alloc] initWithFrame:CGRectMake(width/2 - 32, 120, 64, 64)];
        [self.view addSubview:_groupProtraitView];
    }
    return _groupProtraitView;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
